# -*-coding: Utf-8 -*-
# @File : db_handler .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/10/9
import os
import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import UserModel
from settings import base_settings, mysql_settings,db_settings
import pymysql


class DbHandler():
    def __init__(self):
        # csv 文件根目录
        self.csv_data_dir = os.path.join(db_settings.CSV_DATA_DIR, 'HouseInfoData.csv')
        # 不存在文件则新建文件
        if not os.path.exists(self.csv_data_dir):
            with open(self.csv_data_dir, 'w', encoding='utf-8', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([
                    'house_name',
                    'house_detail_url',
                    'house_detail',
                    'house_area',
                    'house_create',
                    'house_cover',
                    'house_price_total',
                    'house_pre_price',
                    'house_location',
                    'house_tag',
                ])

    def save_row_data(self, row):
        '''

        :param row: 写入每一行的数据
        :return:
        '''
        with open(self.csv_data_dir, 'a', encoding='utf-8', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(row)


class MysqlController():
    def __init__(self, **kwargs):
        self.conn = pymysql.connect(
            user=mysql_settings.MYSQL_USER,
            password=mysql_settings.MYSQL_PASSWORD,
            host=mysql_settings.MYSQL_HOST,
            database=mysql_settings.MYSQL_DATABASE,
            port=mysql_settings.MYSQL_PORT,
            charset=mysql_settings.MYSQL_CHARSET,
            cursorclass=pymysql.cursors.DictCursor, **kwargs
        )
        # 获取游标
        self.cursor = self.conn.cursor()

    # 查询数据
    def query(self, sql, args=None, one=True):
        self.cursor.execute(sql, args)
        if one:
            return self.cursor.fetchone()
        else:
            return self.cursor.fetchall()

    def exec(self, sql):
        res = self.cursor.execute(sql)
        self.conn.commit()
        # self.close()
        return res

    # 关闭数据库连接
    def close(self):
        self.cursor.close()
        self.conn.close()

